using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint.Administration;

namespace TamTam.SharePoint.SolutionManagement.UI {
    
    public class AddSolution:Page {

        protected FileUpload fuSolution;
        protected Button butUpload;
        protected Literal litError;

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);
            butUpload = GetControl("butupload", Page.Controls) as Button;
            fuSolution = GetControl("fusolution", Page.Controls) as FileUpload;
            if (butUpload != null) {
                butUpload.Click += new EventHandler(butUpload_Click);
            }
        }

        protected Control GetControl(string id, ControlCollection controls) {
            Control result = null;
            foreach (Control control in controls) {
                if ((control.ID != null) && (control.ID.ToLower() == id)) {
                    result = control;
                }
                else {
                    result = GetControl(id, control.Controls);
                }
                if (result != null)
                    break;
            }
            return result;
        }

        private void butUpload_Click(object sender, EventArgs e) {
            string error = "";
            if ((fuSolution.FileName == null) || (fuSolution.FileName.Length <1)) {
                error = "No file selected. please select a valid solution file.";
            }
            else {
                if (fuSolution.FileName.ToLower().EndsWith(".wsp")) {

                    try {
                        SolutionHandler.Deploy(fuSolution.FileName, fuSolution.FileBytes,MsBuildTasks.Deployment.Upgrade);
                    }
                    catch (Exception exc) {
                        error = exc.Message;
                        error += "\r\n";
                        error += exc.StackTrace;
                    }                    
                }
                else {
                    error = "No valid solution file selected. Please select a valid solution file.";
                }
            }
            litError.Text = error;
            Diagnostics.Logging.LogMessage(
                "SolutionManagement", 
                "AddSolution", 
                error);
        }
    }
}
